package com.common.www.controller.auth;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.service.auth.AccessService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.auth.AuthAccess;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.utils.R;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@CrossOrigin()
@Api(tags = "MGT 用户权限相关接口")
@RequestMapping(value = {"/mgt/auth/access/"})
public class MGTAccessController extends DefaultCrudController<AuthAccess, Long> {

    @Autowired
    private AccessService accessService;

    @Override
    protected IBaseService getService() {
        return accessService;
    }

    @ApiOperation("添加用户的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        AuthAccess authAccess = JSON.parseObject(json, AuthAccess.class);
        //新增时计算权限名是否重复
        if (authAccess.getId() == null) {
            AuthAccess query = new AuthAccess();
            query.setCdt(null);
            query.setCreateTime(null);
            query.setId(null);
            query.setLastUpdateTime(null);
            query.setName(authAccess.getName());
            Long count = accessService.count(Example.of(query));
            if (count > 0) {
                return R.fail("权限键已存在");
            }
        }


        return super.save(authAccess);
    }
}
